<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<script>
    let cityList = [
        {id: 1, parentId: 0,name: '江苏省'},
        {id: 2,parentId: 0,name: '广东省'},
        {id: 3,parentId: 0,name: '湖南省'},
        {id: 4,parentId: 1,name: '苏州市'},
        {id: 5,parentId: 1,name: '无锡市'},
        {id: 6,parentId: 1,name: '南通市'},
        {id: 7,parentId: 2,name: '广州市'},
        {id: 8,parentId: 2,name: '深圳市'},
        {id: 9,parentId: 3,name: '长沙市'},
        {id: 10,parentId: 4,name: '工业园区'},
        {id: 11,parentId: 4,name: '吴中区'},
        {id: 12,parentId: 4,name: '姑苏区'}
    ];
    //
    let res = [];
    // 遍历数组
    cityList.forEach( (item,index) => {
        // 过滤属性相等增加属性 children
        item.children = cityList.filter((option)=>{
            return item.id == option.parentId
        })
        // parentId等于0 的是第一级数组 添加到新数组
        if(item.parentId == 0){
            res.push(item)
        }
    })
    console.log(res)
    // 递归生成
    function toGenerateTree(pid,arr){
        let res = []
        arr.forEach((item,index)=>{
            if(pid == item.parentId){
                item.children = toGenerateTree(item.id,arr)
                res.push(item)
            }
        })
        return res
    }

    console.log(toGenerateTree(0,cityList))
</script>
</body>
</html>
